package org.example.config;

import org.example.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @Auther: GongXl
 * @Date: 2021/3/13 14:01
 * @Description:授权服务器配置类
 */
//@Configuration
//@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
//    指定Bean位置
    @Qualifier("redisTokenStore")
    private TokenStore tokenStore;
    /**
     * @Author GongXl
     * @Description 授权码模式配置
     * @Date 2021/3/16 14:02
     * @Param [clients]
     * @return void
     **/
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
//                账号
                .withClient("admin")
//                密码
                .secret(passwordEncoder.encode("123456"))
//                重定向地址
                .redirectUris("http://www.baidu.com")
//                授权范围-可访问的资源范围不同，这个是所有
                .scopes("all")
//                授权模式配置，密码模式
                .authorizedGrantTypes("authorization_code","password");
    }
    /**
     * @Author GongXl
     * @Description 密码模式配置
     * @Date 2021/3/16 14:03
     * @Param [endpoints]
     * @return void
     **/
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .userDetailsService(userServiceImpl)
//                授权管理器
                .authenticationManager(authenticationManager)
//                令牌存储位置
                .tokenStore(tokenStore);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}